package com.joshua.spring.util;

import com.joshua.spring.constants.MicroServiceHttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static com.joshua.spring.constants.MicroServiceHttpHeaders.*;
import static com.joshua.spring.constants.MicroServiceHttpHeaders.UNKNOWN;

/**
 * projectName dragon-cloud
 * package com.joshua.spring.util
 * classname  IpAddressUtils
 * <p>
 * description ip地址解析工具类
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/8/31 8:33
 */
public class IpAddressUtils {
    public static String getIpAddress(ServerHttpRequest request) {
        String ip = request.getHeaders().getFirst(MicroServiceHttpHeaders.X_FORWARDED_FOR);
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst(PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst(WL_PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst(HTTP_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst(HTTP_X_FORWARDED_FOR);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getHostString();
        }
        return ip;
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader(MicroServiceHttpHeaders.X_FORWARDED_FOR);
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(WL_PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HTTP_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HTTP_X_FORWARDED_FOR);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
